package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/4/9 20:27
 * @Version 1.0
 */

@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {

    @Override
    public ResponseResult listByName(ChannelDto dto) {
        // 根据频道名称分页查询列表
        LambdaQueryWrapper<WmChannel> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getName().trim())) {
            query.like(WmChannel::getName, dto.getName());
        }
        // 构建分页条件
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());
        // 执行分页查询
        IPage<WmChannel> iPage = this.page(page, query);
        // 构建通用的分页响应
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        return result;

    }

    @Override
    public ResponseResult saveWmChannel(WmChannel entity) {
        //校验参数是否为空
        if (entity == null || StringUtils.isEmpty(entity.getName())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //保存新增的频道
        //判断频道名称是否已经存在在数据库中
        LambdaUpdateWrapper<WmChannel> query = new LambdaUpdateWrapper<>();
        query.eq(WmChannel::getName, entity.getName());
        int count = this.count(query);

        //几经存在不能新增，给前端一个友好提示
        if (count > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
        }
        //不存在,新增
        //创建时间由后台生成
        entity.setCreatedTime(new Date());
        this.save(entity);
        return ResponseResult.okResult();

    }
}
